package com.dreamlin.lindownload.set;

import androidx.annotation.NonNull;

import com.dreamlin.lindownload.LinDownloadTaskImp;

import java.util.Iterator;
import java.util.LinkedList;

public class TaskQueue {

    private LinkedList<String> keys;
    private LinkedList<LinDownloadTaskImp> values;

    public TaskQueue() {
        keys = new LinkedList<>();
        values = new LinkedList<>();
    }

    public void add(@NonNull LinDownloadTaskImp linDownloadTaskImp) {
        keys.add(linDownloadTaskImp.getUrl());
        values.add(linDownloadTaskImp);
    }

    public LinDownloadTaskImp peek() {
        return values.peek();
    }

    public LinDownloadTaskImp poll() {
        keys.poll();
        return values.poll();
    }

    public boolean contains(@NonNull String key) {
        return keys.contains(key);
    }

    public void remove(@NonNull LinDownloadTaskImp linDownloadTaskImp) {
        keys.remove(linDownloadTaskImp.getUrl());
        values.remove(linDownloadTaskImp);
    }

    public void remove(@NonNull String url) {
        if (keys.contains(url)) {
            keys.remove(url);
            Iterator<LinDownloadTaskImp> iterator = values.iterator();
            while (iterator.hasNext()) {
                LinDownloadTaskImp next = iterator.next();
                if (next.getUrl().equals(url))
                    iterator.remove();
            }
        }
    }

    public LinDownloadTaskImp get(@NonNull String key) {
        if (keys.contains(key)) {
            for (LinDownloadTaskImp next : values) {
                if (next.getUrl().equals(key)) {
                    return next;
                }
            }
        }
        return null;
    }

    public int size() {
        return values.size();
    }

}
